import { getLunarDate } from './util.js'

export function generateCalendar(year, month) {
  const days = []
  const firstDay = new Date(year, month - 1, 1)
  const lastDay = new Date(year, month, 0)
  
  // 上月剩余天数
  const prevMonthDays = firstDay.getDay()
  const prevMonthLastDay = new Date(year, month - 1, 0).getDate()
  
  // 填充上月日期
  for (let i = prevMonthDays - 1; i >= 0; i--) {
    const day = prevMonthLastDay - i
    days.push(createDateObject(year, month - 1, day, false))
  }
  
  // 当前月日期
  for (let i = 1; i <= lastDay.getDate(); i++) {
    days.push(createDateObject(year, month, i, true))
  }
  
  // 填充下月日期
  const remainingDays = 42 - days.length
  for (let i = 1; i <= remainingDays; i++) {
    days.push(createDateObject(year, month + 1, i, false))
  }
  
  return days
}

function createDateObject(year, month, day, isCurrentMonth) {
  const date = new Date(year, month - 1, day)
  return {
    year,
    month,
    day,
    weekday: date.getDay(),
    isCurrentMonth,
    lunar: getLunarDate(year, month, day),
    fullDate: `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`
  }
}